package com.fms.fmsapi.controller;

import com.fms.fmsapi.common.config.MinioConfig;
import com.fms.fmsapi.entity.R;
import com.fms.fmsapi.utils.MinioUtil;
import io.minio.messages.Bucket;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;

/**
 * @author Guqier
 * @version 1.0
 * @date 2023/9/28 15:58
 */
@RestController
@RequestMapping(value = "/file")
public class FileController {


    @Autowired
    private MinioUtil minioUtil;
    @Autowired
    private MinioConfig prop;

    @GetMapping("/bucketExists")
    public R bucketExists(@RequestParam("bucketName") String bucketName) {
        return R.success(new HashMap<>(){{
            put("bucketName",minioUtil.bucketExists(bucketName));
        }});
    }

    @GetMapping("/makeBucket")
    public R makeBucket(String bucketName) {
        return R.success(new HashMap<>(){{
            put("bucketName",minioUtil.makeBucket(bucketName));
        }});
    }

    @GetMapping("/removeBucket")
    public R removeBucket(String bucketName) {
        return R.success(new HashMap<>(){{
            put("bucketName",minioUtil.makeBucket(bucketName));
        }});
    }

    @GetMapping("/getAllBuckets")
    public R getAllBuckets() {
        List<Bucket> allBuckets = minioUtil.getAllBuckets();
        return R.success(new HashMap<>(){{
            put("allBuckets",allBuckets);
        }});
    }

    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) {
        String objectName = minioUtil.upload(file);
        if (null != objectName) {
            return prop.getEndpoint() + "/" + prop.getBucketName() + "/" + objectName;
        }
        return null;
    }

    @GetMapping("/preview")
    public R preview(@RequestParam("fileName") String fileName) {
        return R.success(new HashMap<>(){{
            put("filleName",minioUtil.preview(fileName));
        }});
    }

    @GetMapping("/download")
    public R download(@RequestParam("fileName") String fileName, HttpServletResponse res) {
        minioUtil.download(fileName,res);
        return R.success(null);
    }

    @PostMapping("/delete")
    public R remove(String url) {
        String objName = url.substring(url.lastIndexOf(prop.getBucketName()+"/") + prop.getBucketName().length()+1);
        minioUtil.remove(objName);
        return R.success(new HashMap<>(){{
            put("objName",objName);
        }});
    }

}
